//! Deal with the csv file
//!
//! And will convert it to unidata
use json::JsonValue;

use crate::{error::ParserError, utils::ToJsonValue, INDEX_KEY};

use super::Data;

use std::{collections::HashMap, path::Path};

/// Get data for config.file
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Data, ParserError> {
    let mut keys = Vec::new();
    let mut data = Vec::new();
    let csv = quick_csv::Csv::from_file(path)?;

    for row in csv.into_iter() {
        let row = row?;
        let mut columns = row.columns()?;

        if keys.is_empty() {
            while let Some(s) = columns.next() {
                keys.push(s.to_string());
            }
        } else {
            let mut index = 0;
            let mut map = HashMap::new();
            while let Some(s) = columns.next() {
                map.insert(keys[index].to_string(), s.to_json());
                index += 1;
            }
            map.insert(INDEX_KEY.to_string(), JsonValue::from(data.len()));
            data.push(map);
        }
    }

    Ok(Data::from(data))
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_from_file() {
        let data = from_file("examples/user.csv").unwrap();
        println!("{:#?}", data);
    }
}
